package com.schoolhelper.login.controller;

import com.schoolhelper.login.domain.User;
import com.schoolhelper.login.service.AuthService;
import com.schoolhelper.utils.JwtUtils;
import com.schoolhelper.config.FileUploadConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class ProfileController {

    @Autowired
    private AuthService authService;
    
    @Autowired
    private FileUploadConfig fileUploadConfig;

    @Autowired
    private JwtUtils jwtUtils;

    @PutMapping("/profile")
    public Map<String, Object> updateProfile(@RequestBody User user, @RequestHeader("Authorization") String token) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 从token中获取用户ID
            String actualToken = token.replace("Bearer ", "");
            String userId = String.valueOf(jwtUtils.getUserIdFromToken(actualToken));
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的token");
                return response;
            }
            
            // 设置用户ID
            user.setId((long) Integer.parseInt(userId));
            
            // 更新用户信息
            boolean updateResult = authService.updateUserProfile(user);
            
            if (updateResult) {
                response.put("success", true);
                response.put("message", "个人信息更新成功");
            } else {
                response.put("success", false);
                response.put("message", "个人信息更新失败");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "服务器错误，请稍后重试");
            e.printStackTrace();
        }
        
        return response;
    }
    
    @GetMapping("/profile")
    public Map<String, Object> getProfile(@RequestHeader("Authorization") String token) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 从token中获取用户ID
            String actualToken = token.replace("Bearer ", "");
            String userId = String.valueOf(jwtUtils.getUserIdFromToken(actualToken));
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的token");
                return response;
            }
            
            // 获取用户信息
            User user = authService.getUserById(Long.valueOf(userId));
            
            if (user != null) {
                // 处理头像URL
                if (user.getAvatar() != null && !user.getAvatar().isEmpty() && !user.getAvatar().startsWith("http")) {
                    user.setAvatar(fileUploadConfig.getFileUrl(user.getAvatar()));
                }
                
                response.put("success", true);
                response.put("data", user);
            } else {
                response.put("success", false);
                response.put("message", "用户不存在");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "服务器错误，请稍后重试");
            e.printStackTrace();
        }
        
        return response;
    }
    
    @PostMapping("/upload-avatar")
    public Map<String, Object> uploadAvatar(@RequestParam("avatar") MultipartFile file, 
                                           @RequestHeader("Authorization") String token) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证token
            String actualToken = token.replace("Bearer ", "");
            Long userId = jwtUtils.getUserIdFromToken(actualToken);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的token");
                return response;
            }
            
            // 验证文件
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "文件不能为空");
                return response;
            }
            
            // 验证文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                response.put("success", false);
                response.put("message", "文件名无效");
                return response;
            }
            
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            if (!fileUploadConfig.isAllowedFileType(fileExtension)) {
                response.put("success", false);
                response.put("message", "只支持以下格式的图片: " + fileUploadConfig.getAllowedTypes());
                return response;
            }
            
            // 验证文件大小
            if (file.getSize() > fileUploadConfig.getMaxSize()) {
                response.put("success", false);
                response.put("message", "文件大小不能超过" + (fileUploadConfig.getMaxSize() / 1024 / 1024) + "MB");
                return response;
            }
            
            // 创建上传目录
            String uploadPath = fileUploadConfig.getPath();
            File uploadDirFile = new File(uploadPath);
            if (!uploadDirFile.exists()) {
                boolean created = uploadDirFile.mkdirs();
                if (!created) {
                    response.put("success", false);
                    response.put("message", "无法创建上传目录: " + uploadPath);
                    return response;
                }
            }
            
            // 生成唯一文件名
            String uniqueFilename = UUID.randomUUID().toString() + "." + fileExtension;
            
            // 保存文件
            File destFile = new File(uploadPath, uniqueFilename);
            file.transferTo(destFile);
            
            // 构建相对路径（用于数据库存储）
            String relativePath = "/uploads/" + uniqueFilename;
            
            // 获取当前用户并更新头像
            User user = authService.getUserById(userId);
            if (user != null) {
                user.setAvatar(relativePath);
                boolean updateResult = authService.updateUserProfile(user);
                
                if (!updateResult) {
                    response.put("success", false);
                    response.put("message", "头像上传成功，但更新数据库失败");
                    return response;
                }
            } else {
                response.put("success", false);
                response.put("message", "用户不存在");
                return response;
            }
            
            // 返回完整的访问URL
            String fullUrl = fileUploadConfig.getFileUrl(relativePath);
            
            response.put("success", true);
            response.put("message", "头像上传成功");
            response.put("avatarUrl", fullUrl);
            
        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "文件上传失败: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误: " + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }
}